package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"house/models/cache"
	"house/models/mysql"
	"time"

	"house/houserpc/houserpc"
	"house/houserpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type AskListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAskListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AskListLogic {
	return &AskListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AskListLogic) AskList(in *houserpc.AskListRequest) (*houserpc.AskListResponse, error) {
	// todo: add your logic here and delete this line
	var ask []mysql.Ask
	key := fmt.Sprintf("AskList")
	result, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if result != "" {
		json.Unmarshal([]byte(result), &ask)
	} else {
		mysql.DB.Debug().Order("asks.created_at desc").Find(&ask)
		jsonData, _ := json.Marshal(&ask)
		cache.Rdb.Set(cache.Ctx, key, jsonData, time.Minute*15)
	}
	var b []*houserpc.AskList
	for _, c := range ask {
		list := houserpc.AskList{
			UserId:  int64(c.UserId),
			HouseId: int64(c.HouseId),
			Content: c.Content,
			AskTime: c.CreatedAt.Format(time.DateTime),
		}
		b = append(b, &list)
	}
	return &houserpc.AskListResponse{
		List: b,
	}, nil
}
